<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="监测配置编号"
        prop="monitorConfigNo"
        label-width="100px"
      >
        <el-input
          v-model="queryParams.monitorConfigNo"
          placeholder="请输入监测配置编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器名称" prop="instrumentName">
        <el-input
          v-model="queryParams.instrumentName"
          placeholder="请输入仪器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['monitor:config:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['monitor:config:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['monitor:config:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['monitor:config:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="configList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="监测配置编号"
        align="center"
        prop="monitorConfigNo"
      />
      <el-table-column label="仪器编号" align="center" prop="instrumentNo" />
      <el-table-column label="仪器名称" align="center" prop="instrumentName" />
      <el-table-column
        label="仪器状态"
        align="center"
        prop="instrumentStateName"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.instrument_state"
            :value="scope.row.instrumentStateName"
          />
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column label="轮询周期" align="center" prop="pollingCycle" />
      <el-table-column label="阈值" align="center" prop="threshold" />
      <el-table-column label="启用" align="center" prop="enableType" />
      <el-table-column label="备注" align="center" prop="remarks" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['monitor:config:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['monitor:config:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 选择仪器编号对话框 -->
    <el-dialog
      title="选择仪器编号"
      :visible.sync="instrumentDialogVisible"
      width="80%"
    >
      <instrument-data
        ref="instrumentDataRef"
        :is-row-visible="false"
        @selection-change="handleRowSelection"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="chooseInstrument">确 定</el-button>
        <el-button @click="instrumentDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改监测配置对话框 -->
    <el-drawer :title="title" :visible.sync="open" size="400px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="padding-right: 20px"
      >
        <!-- <el-form-item label="监测配置编号" prop="monitorConfigNo">
          <el-input
            v-model="form.monitorConfigNo"
            placeholder="请输入监测配置编号"
          />
        </el-form-item> -->
        <el-form-item label="部门名称" prop="departmentName">
          <el-select
            v-model="form.departmentName"
            size="small"
            placeholder="请选择部门"
            clearable
            @change="handleDepartmentChange"
          >
            <el-option
              v-for="item in options.departments"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仪器编号" prop="instrumentNo">
          <el-input
            readonly
            v-model="form.instrumentNo"
            placeholder="请选择仪器编号"
            @click.native="instrumentDialogVisible = true"
            class="pointer-input"
          >
            <!-- 添加选择图标 -->
            <i slot="suffix" class="el-icon-search el-input__icon"></i>
          </el-input>
        </el-form-item>
        <el-form-item label="仪器名称" prop="instrumentName">
          <el-input
            v-model="form.instrumentName"
            placeholder="请输入仪器名称"
          />
        </el-form-item>
        <!-- <el-form-item label="仪器状态代码" prop="instrumentStateCode">
          <el-input
            v-model="form.instrumentStateCode"
            placeholder="请输入仪器状态代码"
          />
        </el-form-item> -->
        <el-form-item label="仪器状态" prop="instrumentStateName">
          <el-radio-group v-model="form.instrumentStateName">
            <el-radio
              v-for="dict in dict.type.instrument_state"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="轮询周期" prop="pollingCycle">
          <el-input v-model="form.pollingCycle" placeholder="请输入轮询周期" />
        </el-form-item>
        <el-form-item label="阈值" prop="threshold">
          <el-input v-model="form.threshold" placeholder="请输入阈值" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listConfig,
  getConfig,
  delConfig,
  addConfig,
  updateConfig,
} from "@/api/monitor/config";
import InstrumentData from "@/views/instrument/data/index.vue";
import { listDept } from "@/api/system/dept";

export default {
  name: "Config",
  dicts: ["instrument_state"],
  components: {
    InstrumentData,
  },
  data() {
    return {
      selectedInstrumentData: null, // 选中的仪器数据
      instrumentDialogVisible: false,
      options: {
        departments: [], // 部门列表
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监测配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        monitorConfigNo: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        instrumentStateCode: null,
        instrumentStateName: null,
        pollingCycle: null,
        threshold: null,
        enableType: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        monitorConfigNo: [
          { required: true, message: "监测配置编号不能为空", trigger: "blur" },
        ],
        departmentName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
        ],
        departmentId: [
          { required: true, message: "部门id不能为空", trigger: "blur" },
        ],
        instrumentId: [
          { required: true, message: "仪器id不能为空", trigger: "blur" },
        ],
        instrumentNo: [
          { required: true, message: "仪器编号不能为空", trigger: "blur" },
        ],
        instrumentName: [
          { required: true, message: "仪器名称不能为空", trigger: "blur" },
        ],
        instrumentStateCode: [
          { required: true, message: "仪器状态代码不能为空", trigger: "blur" },
        ],
        instrumentStateName: [
          {
            required: true,
            message: "仪器状态名称不能为空",
            trigger: "change",
          },
        ],
        pollingCycle: [
          { required: true, message: "轮询周期不能为空", trigger: "blur" },
        ],
        threshold: [
          { required: true, message: "阈值不能为空", trigger: "blur" },
        ],
        enableType: [
          { required: true, message: "启用不能为空", trigger: "change" },
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" },
        ],
        creatorId: [
          { required: true, message: "新增人id不能为空", trigger: "blur" },
        ],
        creator: [
          { required: true, message: "新增人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "新增时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDepartments();
  },
  methods: {
    chooseInstrument() {
      const selectedInstrument = this.selectedInstrumentData;
      if (selectedInstrument) {
        this.form.instrumentId = selectedInstrument.instrumentId;
        this.form.instrumentNo = selectedInstrument.instrumentNo;
        this.form.instrumentName = selectedInstrument.instrumentName;
        this.instrumentDialogVisible = false; // 关闭对话框
      } else {
        this.$modal.msgError("请先选择一个仪器");
      }
    },
    handleRowSelection(selection) {
      const tableRef = this.$refs.instrumentDataRef.$refs.instrumentTable;
      if (selection.length > 1) {
        const lastSelected = selection[selection.length - 1];
        this.$nextTick(() => {
          tableRef.clearSelection(); // 清除所有选中
          tableRef.toggleRowSelection(lastSelected, true); // 仅保留当前选中
        });
        this.selectedInstrumentData = lastSelected;
      } else {
        this.selectedInstrumentData = selection[0] || null;
      }
      console.log("查看选中的仪器数据", this.selectedInstrumentData);
    },
    handleDepartmentChange(deptName) {
      const dept = this.options.departments.find(
        (dept) => dept.deptName === deptName
      );
      if (dept) {
        this.form.departmentId = dept.deptId;
      } else {
        this.$modal.msgError("部门不存在");
        this.form.departmentId = null;
      }
    },
    async getDepartments() {
      try {
        const response = await listDept(); // 替换为实际的部门列表API
        this.options.departments = response.data;
        console.log("获取部门列表成功:", response.data);
      } catch (error) {
        console.error("获取部门列表失败:", error);
      }
    },
    /** 查询监测配置列表 */
    getList() {
      this.loading = true;
      listConfig(this.queryParams).then((response) => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        monitorConfigId: null,
        monitorConfigNo: null,
        departmentName: null,
        departmentId: null,
        instrumentId: null,
        instrumentNo: null,
        instrumentName: null,
        instrumentStateCode: null,
        instrumentStateName: null,
        pollingCycle: null,
        threshold: null,
        enableType: null,
        remarks: null,
        isDelete: null,
        creatorId: null,
        creator: null,
        createTime: null,
        modifierId: null,
        modifier: null,
        modifyTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.monitorConfigId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监测配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const monitorConfigId = row.monitorConfigId || this.ids;
      getConfig(monitorConfigId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改监测配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.instrumentStateCode =
        this.form.instrumentStateName === "在线" ? "01" : "02";
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.monitorConfigId != null) {
            updateConfig(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const monitorConfigIds = row.monitorConfigId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除监测配置编号为"' + monitorConfigIds + '"的数据项？'
        )
        .then(function () {
          return delConfig(monitorConfigIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "monitor/config/export",
        {
          ...this.queryParams,
        },
        `config_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.drawer-footer {
  /* width: 100%; */
  position: absolute;
  right: 10px;
  bottom: 10px;
}
</style>
